
"""
创建sessionId
"""
import json
from retry import retry
from fake_useragent import UserAgent
import requests


class AgentService(object):

    base_url = 'http://172.18.0.66'

    def __init__(self):
        self.token = None
        self.refresh_token()

    @retry(tries=5, delay=0)
    def refresh_token(self):
        login_url = f"{self.base_url}/dianda/uis/oauth2/token"
        headers = {
            "Authorization": "Basic dS1jbGllbnQ6MTIzNDU2",
            "User-Agent": UserAgent().random,
        }
        data = {
            "grant_type": "password",
            "username": "superuser",
            "password": "Maiyue!56789@"
        }
        req = requests.post(login_url, headers=headers, data=data, verify=False)
        try:
            result = req.json()['data']
            self.token = f'{result["token_type"]} {result["access_token"]}'
        except Exception as e:
            pass

    def call_agent(self, data):
        query_url = f"{self.base_url}/dianda/ai/agent/smartagent/createSession"
        headers = {
            "authorization": self.token,
            "User-Agent": UserAgent().random,
            "Content-Type": "application/json"
        }
        req = requests.post(
            query_url, headers=headers, data=json.dumps(data)
        )
        return req.json()

agent_service = AgentService()